const jwt = require("jsonwebtoken");
const { authExpiredError, authInvalidError } = require("../constant/errorType");

const auth = async (ctx, next) => {
  const { authorization = "" } = ctx.request.header;
  const token = authorization.replace("Bearer ", "");
  try {
    const userInfo = jwt.verify(token, process.env.JWT_SECRET);
    ctx.state.userInfo = userInfo;
  } catch (error) {
    switch (error.name) {
      case "TokenExpiredError":
        return ctx.app.emit(
          "error",
          { ...authExpiredError, message: error },
          ctx
        );
      default:
        // case "JsonWebTokenError":
        return ctx.app.emit(
          "error",
          { ...authInvalidError, message: error },
          ctx
        );
    }
  }

  await next();
};

module.exports = { auth };
